<template>
    <div class="user-info-page">
        <!-- 页面标题 -->
        <div class="page-header">
            <h2>用户信息详情</h2>
            <el-divider />
        </div>

        <!-- 加载状态 -->
        <el-skeleton v-if="loading" class="skeleton-container" :rows="8" :columns="2" />

        <!-- 用户信息渲染区（卡片式布局） -->
        <el-card v-else class="user-info-card" shadow="hover">
            <!-- 头像与基础信息区 -->
            <div class="user-basic-section">
                <el-avatar :size="80" :src="userInfo.imgpath" class="user-avatar-large">
                </el-avatar>

                <div class="basic-info">
                    <h3 class="user-name">{{ userInfo.username }}</h3>
                </div>
            </div>

            <el-divider />

            <!-- 详细信息表格 -->
            <el-table :data="userInfoTableData" border :show-header="false" class="user-info-table">
                <el-table-column prop="label" width="120" align="center" class="table-label" />
                <el-table-column prop="value" class="table-value" />
            </el-table>

            <!-- 操作按钮区 -->
            <div class="action-buttons">
                <el-button type="primary" @click="handleEdit">编辑信息</el-button>
            </div>
        </el-card>
        <!-- 修改对话框 -->

        <div>
            <!-- 修改用户和修改对话框 -->
            <el-dialog v-model="dialog.visible" :title="dialog.title" width="25%" draggable :show-close="false"
                :close-on-click-modal="false" :close-on-press-escape="false">
                <!-- 新增用户表单 -->
                <el-form :inline="true" :model="dialog.user" class="demo-form-inline">
                    <el-form-item>
                        <h1>{{ store.userinfo.username }}</h1>
                    </el-form-item>
                    <!-- 显示上传图片 -->
                    <div
                        style="position:  absolute;top: 50px;left: 240px; width: 30%; height: 100px;background-color:#FAFAFA ;text-align: center;border-radius: 5px;">
                        <el-image @click="showUploadImageDialog()" :src="dialog.user.imgpath"
                            style="border-radius: 5%;width: 100%;" />
                        <!-- <el-button @click="showUploadImageDialog()"
                        style="width: 90px;height: 10px;background-color: #FAFAFA;line-height: 10px;font-size: 12px;">添加图片</el-button> -->
                    </div>

                    <!-- <el-select v-model="dialog.user.rid" placeholder="选择用户类型" clearable style="width: 200px;">
                    
                    <el-option label="管理员" :value="102" />
                    <el-option label="vip用户" :value="101" />
                    <el-option label="普通用户" :value="100" />
                </el-select> -->
                    <el-input v-model="dialog.user.email" :rows="2" placeholder="输入邮箱"
                        style="width: 340px;margin-top: 20px;" />
                    <el-input v-model="dialog.user.phone" :rows="2" placeholder="输入电话"
                        style="width: 340px;margin-top: 20px;" />
                    <el-form-item style="margin-top: 20px;">
                        <el-button type="primary" @click="insertAndUpdateUser">修改</el-button>
                        <el-button type="primary" @click="clearFormData">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>

        <div>
            <!-- 修改用户和修改对话框 -->
            <el-dialog v-model="uploadDialog.visible" title="文件上传" width="30%" draggable>
                <el-upload :action="uploadDialog.uploadUrl" list-type="picture-card" :file-list="fileList"
                    :limit="uploadDialog.limit" :auto-upload="uploadDialog.autoUpload" :on-change="handlerImage">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
                <!-- 添加上传按钮 -->
                <el-form-item style="margin-top: 10px;margin-left: 320px;">
                    <el-button type="primary" @click="uploadHandler()">上传</el-button>
                </el-form-item>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from 'vue';
import { useUserStore } from '@/stores/userStore';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';

// 1. 状态管理
const store = useUserStore();
const loading = ref(false); // 加载状态
const errorMsg = ref(''); // 错误信息
// 2. 用户信息数据模型（与t_user表字段对应）
const userInfo = ref({
    uid: '',
    username: '',      // 用户名
    email: '',         // 邮箱
    phone: '',         // 手机号
    imgpath: '',       // 头像路径
    accident_count: 0,  // 事故次数
    password: '',
});

// 3. 表格化数据（与t_user表字段对应）
const userInfoTableData = computed(() => [
    { label: '用户id', value: userInfo.value.uid || '未设置' },
    { label: '用户名', value: userInfo.value.username || '未设置' },
    { label: '手机号', value: userInfo.value.phone || '未绑定' },
    { label: '邮箱', value: userInfo.value.email || '未绑定' },
    { label: '事故次数', value: userInfo.value.accident_count || 0 }
]);

// 4. 核心方法：根据用户名查询用户信息
const getUserInfoByUsername = async () => {
    // 校验用户名是否存在（从store获取）
    const username = store.userinfo.username;

    if (!username) {
        errorMsg.value = '用户名不能为空（未从store获取到有效用户名）';
        return;
    }

    try {
        loading.value = true;
        errorMsg.value = ''; // 重置错误信息
        const res = await request.get(`/user/findByName/${username}`);
        // 接口成功处理
        if (res.data.success) {
            console.log('用户信息:', res.data.data);
            userInfo.value = res.data.data; // 赋值用户信息
            ElMessage({ type: 'success', message: '获取用户信息成功' });
        }
    } catch (err) {

    } finally {
        loading.value = false; // 关闭加载状态
    }
};
//定义对话框属性
const dialog = ref({
    visible: false,
    title: '',
    btnText: '',
    user: {},
})
//定义变量控制文件上传
const uploadDialog = reactive({
    visible: false, //隐藏对话框
    uploadUrl: "",
    fileList: [], //保存所有上传文件集合
    limit: 1,//控制文件上传个数
    autoUpload: false,
    uploadFile: null,
})
//实现用户新增或者修改操作
const insertAndUpdateUser = async () => {
    //1.获取数据发送请求实现修改用户信息
    let res = await request.put("/user/updateTwo", dialog.value.user);

    //判断是否新增成功
    if (res.data.success) {
        //1.清空表单
        clearFormObj();
        //2.刷新页面
        await getUserInfoByUsername();
        //3.显示提示信息
        ElMessage.success("修改成功")
        //4.关闭对话框
        dialog.value.visible = false;
    }
}
//显示文件上传对话框
const showUploadImageDialog = () => {
    uploadDialog.visible = true;
}

//选中文件时触发函数
const handlerImage = (file) => {
    uploadDialog.uploadFile = file.raw;
}
const clearFormData = () => {
    dialog.value.visible = false; // 关闭对话框
}
//清空表单函数
const clearFormObj = () => {
    dialog.value.user.username = '';
    dialog.value.user.rid = 100;
    dialog.value.user.email = '';
    dialog.value.user.imgpath = 'https://org-yixue-ykj-bucket.oss-cn-nanjing.aliyuncs.com/avatar/cxy.jpg';
    dialog.value.user.phone = '';
    dialog.value.user.uid = '';
}
//实现文件上传函数
const uploadHandler = async () => {
    //文件上传详细步骤
    //1.创建FormData对象
    let formData = new FormData();
    //2.设置上传对象对象
    formData.append("file", uploadDialog.uploadFile)
    //3.设置上传类型
    let contentType = { "ContentType": "multipart/form-data" }
    formData.append("headers", contentType);
    //4.发送请求实现文件上传
    let res = await request.post("/user/fileUpload", formData);
    if (res.data.success) {
        //把上传文件保存到表单imgPath中
        dialog.value.user.imgpath = res.data.data; //http://localhost:80/xxxx.png
        //显示提示信息
        ElMessage.success("上传成功");
        //关闭文件上传对话框
        uploadDialog.visible = false;
    }
}

// 5. 操作按钮方法
const handleEdit = async () => {

    //设置按钮文本内容
    dialog.value.btnText = "更新数据";
    //显示对话框
    dialog.value.visible = true;
};

// 6. 页面挂载时自动查询
onMounted(() => {
    getUserInfoByUsername();
});
</script>

<style scoped>
.user-info-page {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 150px);
}

.page-header h2 {
    color: #1e40af;
    font-weight: 600;
    margin-bottom: 10px;
}

/* 加载骨架屏样式 */
.skeleton-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
}

/* 错误提示样式 */
.error-container {
    margin: 50px auto;
    max-width: 500px;
}

.error-detail {
    color: #dc2626;
    font-size: 12px;
    margin-top: 10px;
    text-align: center;
}

/* 用户信息卡片样式 */
.user-info-card {
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
}

/* 基础信息区样式 */
.user-basic-section {
    display: flex;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #eee;
    gap: 20px;
}

.user-avatar-large {
    border: 2px solid #e0e7ff;
}

.avatar-fallback {
    font-size: 32px;
    color: #1e40af;
}

.basic-info .user-name {
    font-size: 20px;
    color: #1e40af;
    margin-bottom: 5px;
}

/* 用户信息表格样式 */
.user-info-table {
    margin: 20px;
    font-size: 14px;
}

.table-label {
    color: #64748b;
    background-color: #f8fafc;
    font-weight: 500;
}

.table-value {
    color: #1e293b;
}

/* 操作按钮区样式 */
.action-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 15px 20px;
    border-top: 1px solid #eee;
}
</style>
